package com.lagou.service.impl;

import com.lagou.dao.TokenDao;
import com.lagou.pojo.Token;
import com.lagou.service.TokenService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;

import java.util.Optional;
import java.util.UUID;

@Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    private TokenDao tokenDao;

    @Override
    public String genToken(String email, String password) {
        //使用uuid生成token
        String token = UUID.randomUUID().toString();
        //保存token到数据库
        Token tokenObj = new Token();
        tokenObj.setEmail(email);
        tokenObj.setToken(token);
        tokenDao.save(tokenObj);
        return token;
    }

    @Override
    public Token getByToken(String token) {
        Token condition = new Token();
        condition.setToken(token);
        Example<Token> example = Example.of(condition);
        Optional<Token> optional = tokenDao.findOne(example);
        if (optional.isEmpty()){
            return null;
        }
        return optional.get();
    }
}
